//
//  NIDropDown.m
//  TianjinAirline
//
//  Created by tan xin on 13-10-29.
//  Copyright (c) 2013年 eKing Technology. All rights reserved.
//

#import "NIDropDown.h"
#import "QuartzCore/QuartzCore.h"
#import "AppDelegate.h"

@interface NIDropDown () <UIGestureRecognizerDelegate>
@property(nonatomic, strong) UITableView *table;    //一级列表
@property(nonatomic, strong) UITableView *detailTable; //二级列表
@property(nonatomic, strong) UIButton *btnSender;
@property(nonatomic, strong) NSArray *list; //一级列表的数据源
@property(nonatomic, strong) NSArray *detailList; //二级列表的数据源
@property(nonatomic, strong) NSArray *imageList; //一级列表的图片

@property (nonatomic, assign) NSInteger selectedRow; //一级列表选中的行
@property (nonatomic, assign) NSInteger selectedDetailRow; //二级列表选中的行

@property (nonatomic, strong) UIWindow *dropListWindow;

@property (nonatomic, strong) UITapGestureRecognizer *recognizer;
@end

@implementation NIDropDown
@synthesize table;
@synthesize detailTable;
@synthesize btnSender;
@synthesize list;
@synthesize detailList;
@synthesize imageList;
@synthesize delegate;
@synthesize direction;

- (id)showDropDownFrom:(UIButton *)btn
            menuHeight:(CGFloat *)height
                titles:(NSArray *)arr
                 icons:(NSArray *)imgArr
             direction:(MenuPopupDirection)dir {
    btnSender = btn;
    self.direction = dir;
    self.table = (UITableView *)[super init];
    if (self) {
        // Initialization code
        if (!self.dropListWindow) {
            self.dropListWindow = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
            self.dropListWindow.windowLevel = UIWindowLevelStatusBar;
            self.dropListWindow.backgroundColor = [UIColor clearColor];
        }

        CGRect btnFrame = [btn.superview convertRect:btn.frame toView:self.dropListWindow];
              
        self.list = [NSArray arrayWithArray:arr];
        self.imageList = [NSArray arrayWithArray:imgArr];
        if (self.direction == PopupMenuUp) {
            self.frame = CGRectMake(btnFrame.origin.x, btnFrame.origin.y, btnFrame.size.width, 0);
            self.layer.shadowOffset = CGSizeMake(-5, -5);
        } else {
            self.frame = CGRectMake(btnFrame.origin.x, btnFrame.origin.y + btnFrame.size.height, btnFrame.size.width, 0);
            self.layer.shadowOffset = CGSizeMake(2, 5);
        }
        
        self.layer.masksToBounds = NO;
        self.layer.cornerRadius = 8;
        self.layer.shadowRadius = 3;
        self.layer.shadowOpacity = 0.3;
        
        table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, btnFrame.size.width, 0)];
        table.delegate = self;
        table.dataSource = self;
        table.scrollEnabled = YES;
        table.layer.cornerRadius = 5;
//        table.backgroundColor = [UIColor colorWithRed:0.239 green:0.239 blue:0.239 alpha:1];
        table.backgroundColor = [UIColor whiteColor];
        table.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        table.separatorColor = [UIColor grayColor];
        
        if (!iOS6) {
            table.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        }
        
        
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5];
        if (self.direction == PopupMenuUp) {
            self.frame = CGRectMake(btnFrame.origin.x, btnFrame.origin.y - *height, btnFrame.size.width, *height);
        } else {
            self.frame = CGRectMake(btnFrame.origin.x, btnFrame.origin.y + btnFrame.size.height, btnFrame.size.width, *height);
        }
        
        table.frame = CGRectMake(0, 0, btnFrame.size.width, *height);
        [UIView commitAnimations];
        
        [self.dropListWindow addSubview:self];
        [self.dropListWindow makeKeyAndVisible];
        
        [self addSubview:table];
        
        self.recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        self.recognizer.delegate = self;
        [self.dropListWindow addGestureRecognizer:_recognizer];
        
        self.isPoped = YES;
        
        self.selectedRow = 0;
        self.selectedDetailRow = -1;
    }
    return self;
}

/**
 *  扩展的下拉列表，支持二级子列表
 *
 *  @param btn       触发的控件
 *  @param height    下拉列表的高度
 *  @param arr       一级列表的标题
 *  @param subTitles 一级列表各行对应的二级子列表标题
 *  @param dir       弹出方向
 *
 *  @return 生成的弹出控件
 */
- (id)showDropDownFrom:(UIButton *)btn
            menuHeight:(CGFloat *)height
                titles:(NSArray *)arr
             subTitles:(NSArray *)subTitles
             direction:(MenuPopupDirection)dir {
    
    btnSender = btn;
    self.direction = dir;
    self.table = (UITableView *)[super init];
    self.detailTable = (UITableView *)[super init];
    if (self) {
        // Initialization code
        if (!self.dropListWindow) {
            self.dropListWindow = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
            self.dropListWindow.windowLevel = UIWindowLevelStatusBar;
            self.dropListWindow.backgroundColor = [UIColor clearColor];
        }
        
        CGRect btnFrame = [btn.superview convertRect:btn.frame toView:self.dropListWindow];
        
        self.list = [NSArray arrayWithArray:arr];
        self.detailList = [NSArray arrayWithArray:subTitles];
        
        if (self.direction == PopupMenuUp) {
            self.frame = CGRectMake(0, btnFrame.origin.y, CGRectGetWidth(self.dropListWindow.bounds), 0);
            self.layer.shadowOffset = CGSizeMake(-5, -5);
        } else {
            self.frame = CGRectMake(0, btnFrame.origin.y + btnFrame.size.height,
                                    CGRectGetWidth(self.dropListWindow.bounds), 0);
            self.layer.shadowOffset = CGSizeMake(2, 5);
        }
        
        self.layer.masksToBounds = NO;
        self.layer.cornerRadius = 3;
        self.layer.shadowRadius = 1;
        self.layer.shadowOpacity = 0.3;
        
        table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.dropListWindow.bounds) * 0.5, 0)];
        table.delegate = self;
        table.dataSource = self;
        table.scrollEnabled = YES;
        table.backgroundColor = [UIColor lightGrayColor];
        table.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        table.separatorColor = [UIColor clearColor];
        
        detailTable = [[UITableView alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.dropListWindow.bounds) * 0.5, 0, CGRectGetWidth(self.dropListWindow.bounds) * 0.5, 0)];
        detailTable.delegate = self;
        detailTable.dataSource = self;
        detailTable.scrollEnabled = YES;
        detailTable.backgroundColor = [UIColor whiteColor];
        detailTable.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        detailTable.separatorColor = [UIColor clearColor];
        
        [self.dropListWindow addSubview:self];
        [self.dropListWindow makeKeyAndVisible];
        [self addSubview:table];
        [self addSubview:detailTable];
        
        float tableHeight = *height;
        
        UIView *coverV = [[UIView alloc] initWithFrame:CGRectMake(0, tableHeight,
                                                                  CGRectGetWidth(self.dropListWindow.bounds),
                                                                  CGRectGetHeight(self.dropListWindow.bounds) - *height)];
        coverV.backgroundColor = [UIColor blackColor];
        coverV.tag = 1001;
        [self addSubview:coverV];
        coverV.alpha = 0.0;
        
        [UIView animateWithDuration:0.5 animations:^{
            if (self.direction == PopupMenuUp) {
                self.frame = CGRectMake(0, btnFrame.origin.y - tableHeight, CGRectGetWidth(self.dropListWindow.bounds), tableHeight);
            } else {
                self.frame = CGRectMake(0, btnFrame.origin.y + btnFrame.size.height, CGRectGetWidth(self.dropListWindow.bounds), tableHeight);
            }
            table.frame = CGRectMake(0, 0, CGRectGetWidth(self.dropListWindow.bounds) * 0.5, tableHeight);
            detailTable.frame = CGRectMake(CGRectGetWidth(self.dropListWindow.bounds) * 0.5, 0,
                                           CGRectGetWidth(self.dropListWindow.bounds) * 0.5, tableHeight);
            
            coverV.alpha = 0.6;
            
        } completion:^(BOOL finished) {
            if (finished) {
                
            }
        }];

        self.recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        self.recognizer.delegate = self;
        [self.dropListWindow addGestureRecognizer:_recognizer];
        
        self.isPoped = YES;
        
        self.selectedRow = 0;
        self.selectedDetailRow = -1;
    }
    return self;
}

- (void)tapAction:(UITapGestureRecognizer *)recognizer {
    [self hideDropDown:btnSender];
}

-(void)hideDropDown:(UIButton *)btn {
    CGRect btnFrame = [btn.superview convertRect:btn.frame toView:self.dropListWindow];
    UIView *coverV = [self viewWithTag:1001];
    [UIView animateWithDuration:0.5 animations:^{
        if (self.direction == PopupMenuUp) {
            self.frame = CGRectMake(0, btnFrame.origin.y, CGRectGetWidth(self.dropListWindow.bounds), 0);
        } else {
            self.frame = CGRectMake(0, btnFrame.origin.y + btnFrame.size.height, CGRectGetWidth(self.dropListWindow.bounds), 0);
        }
        table.frame = CGRectMake(btnFrame.origin.x, 0, btnFrame.size.width, 0);
        detailTable.frame = CGRectMake(CGRectGetWidth(self.dropListWindow.bounds) * 0.5, 0,
                                       CGRectGetWidth(self.dropListWindow.bounds) * 0.5, 0);
        
        coverV.alpha = 0.0;
        
    } completion:^(BOOL finished) {
        if (finished) {
            [self removeFromSuperview];
            self.dropListWindow = nil;
            AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [app.window makeKeyAndVisible];
            
            self.isPoped = NO;
        }
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([tableView isEqual:self.table]) {
        return [self.list count];
    } else if ([tableView isEqual:self.detailTable]) {
        NSInteger num = 0;
        if (self.selectedRow >= 0 && [self.detailList count] > self.selectedRow) {
            NSArray *arr = [self.detailList objectAtIndex:self.selectedRow];
            num = [arr count];
        }
        return num;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.textLabel.minimumFontSize = 9;
        cell.textLabel.adjustsFontSizeToFitWidth = YES;
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.textColor = [UIColor blackColor];
    }
    
//    UIColor *customLightGray = [UIColor colorWithRed:216.0/255.0 green:216.0/255.0 blue:216.0/255.0 alpha:1.0];
    
    NSInteger row = indexPath.row;
    if ([tableView isEqual:self.table]) { //一级列表
        
        cell.backgroundColor = [UIColor whiteColor];
        
        UIView * v = [[UIView alloc] init];
        v.backgroundColor = [UIColor whiteColor];
        v.alpha = 0.7;
        cell.selectedBackgroundView = v;
        cell.textLabel.highlightedTextColor = [UIColor blackColor];
        
        if ([self.detailList count] > self.selectedRow) {
            NSArray *datas = [self.detailList objectAtIndex:row];
            
            if ([datas count] > 0) {
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            } else {
                cell.accessoryType = UITableViewCellAccessoryNone;
            }
        }
        
        if ([self.list count] > row) {
            cell.textLabel.text =[list objectAtIndex:row];
        }
        
        if ([self.imageList count] > row) {
            cell.imageView.image = [imageList objectAtIndex:row];
        }
        
    } else if ([tableView isEqual:self.detailTable]) { //二级列表
        
        cell.backgroundColor = [UIColor whiteColor];
        
        UIView * v = [[UIView alloc] init];
        v.backgroundColor = [UIColor whiteColor];
        v.alpha = 0.7;
        cell.selectedBackgroundView = v;
        
        if ([self.detailList count] > self.selectedRow) {
            NSArray *datas = [self.detailList objectAtIndex:self.selectedRow];
            
            if ([datas count] > row) {
                cell.textLabel.text = [datas objectAtIndex:row];
            }
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger row = indexPath.row;
    if ([tableView isEqual:self.table]) { //一级列表
        self.selectedRow = row;
        
        BOOL hasSubLevel = NO;
        if ([self.detailList count] > self.selectedRow) {
            NSArray *datas = [self.detailList objectAtIndex:self.selectedRow];
            
            if ([datas count] > 0) {
                hasSubLevel = YES;
            }
        }
        
        if (hasSubLevel) {
            [self.detailTable reloadData];
            self.detailTable.separatorColor = [UIColor lightGrayColor];
        } else {
            [self hideDropDown:btnSender];
            
            if (self.delegate != nil && [self.delegate respondsToSelector:@selector(niDropDownDelegateMethod:didSelectedRow:)]) {
                [self.delegate niDropDownDelegateMethod:self didSelectedRow:self.selectedRow];
            }
        }
    } else if ([tableView isEqual:self.detailTable]) {
        [self hideDropDown:btnSender];
        
        if (self.delegate != nil && [self.delegate respondsToSelector:@selector(niDropDownDelegateMethod:didSelectedRow:detailRow:)]) {
            [self.delegate niDropDownDelegateMethod:self didSelectedRow:self.selectedRow detailRow:row];
        }
    }
}

#pragma mark -
#pragma UIGestureRecognizer Delegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]] && (self.dropListWindow != nil)) {
        CGPoint touchPoint = [touch locationInView:self.dropListWindow];
        if (CGRectContainsPoint(self.frame, touchPoint)) {
            return NO;
        } else {
            return YES;
        }
    }
    return NO;
}

@end
